package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ServiceProvider;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.ServiceProviderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * 服务人员管理Controller
 */
@RestController
@RequestMapping("/system/provider")
public class ServiceProviderController extends BaseController {
    
    @Autowired
    private ServiceProviderMapper serviceProviderMapper;
    
    /**
     * 查询服务人员列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ServiceProvider serviceProvider) {
        startPage();
        List<ServiceProvider> list = serviceProviderMapper.selectServiceProviderList(serviceProvider);
        return getDataTable(list);
    }
    
    /**
     * 导出服务人员列表
     */
    @PreAuthorize("@ss.hasPermi('system:provider:export')")
    @Log(title = "服务人员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ServiceProvider serviceProvider) {
        List<ServiceProvider> list = serviceProviderMapper.selectServiceProviderList(serviceProvider);
        ExcelUtil<ServiceProvider> util = new ExcelUtil<>(ServiceProvider.class);
        return util.exportExcel(list, "服务人员数据");
    }
    
    /**
     * 获取服务人员详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(serviceProviderMapper.selectServiceProviderById(id));
    }
    
    /**
     * 新增服务人员
     */
    @PreAuthorize("@ss.hasPermi('system:provider:add')")
    @Log(title = "服务人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ServiceProvider serviceProvider) {
        return toAjax(serviceProviderMapper.insertServiceProvider(serviceProvider));
    }
    
    /**
     * 修改服务人员
     */
    @PreAuthorize("@ss.hasPermi('system:provider:edit')")
    @Log(title = "服务人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ServiceProvider serviceProvider) {
        return toAjax(serviceProviderMapper.updateServiceProvider(serviceProvider));
    }
    
    /**
     * 删除服务人员
     */
    @PreAuthorize("@ss.hasPermi('system:provider:remove')")
    @Log(title = "服务人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(serviceProviderMapper.deleteServiceProviderByIds(ids));
    }
    
    /**
     * 获取推荐服务人员
     */
    @GetMapping("/recommended")
    public AjaxResult getRecommendedProviders() {
        List<ServiceProvider> list = serviceProviderMapper.selectRecommendedServiceProviderList(true);
        return AjaxResult.success(list);
    }
    
    /**
     * 上传服务人员头像
     */
    @PreAuthorize("@ss.hasPermi('system:provider:edit')")
    @Log(title = "服务人员管理", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        
        try {
            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            
            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;
            
            // 设置上传目录
            String uploadDir = "D:/ruoyi/uploadPath/avatar/";
            Path uploadPath = Paths.get(uploadDir);
            
            // 如果目录不存在，创建目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 保存文件
            Path filePath = uploadPath.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath);
            
            // 返回文件访问路径
            String fileUrl = "/profile/avatar/" + newFilename;
            return AjaxResult.success("上传成功", fileUrl);
        } catch (IOException e) {
            logger.error("上传头像失败: ", e);
            return AjaxResult.error("上传头像失败：" + e.getMessage());
        }
    }
}